package scatter.interview.rest.interview.i4_socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by yangwei
 * Created at 2020/12/4 10:37
 */
public class SocketServer {
    // Choose a port outside of the range1-1024:
    public static final int PORT = 8088;
    public static void main(String[] args)
            throws IOException {
        ServerSocket s = new ServerSocket(PORT);
        System.out.println("Started: " + s);
        try {
            Socket socket = s.accept();
            try {
                System.out.println(
                        "Connection accepted: "+ socket);
                BufferedReader KeyIn = new BufferedReader(new InputStreamReader(System.in));

                BufferedReader in =
                        new BufferedReader(
                                new InputStreamReader(
                                        socket.getInputStream()));
                // Output is automatically flushed
                // by PrintWriter:
                PrintWriter out =
                        new PrintWriter(
                                new BufferedWriter(
                                        new OutputStreamWriter(
                                                socket.getOutputStream())),true);
                while (true) {
                    String str = in.readLine();
                    if ("END".equals(str)){
                        break;
                    }
                    System.out.println("Client: " + str);
                    out.println(KeyIn.readLine());

                }
                // Always close thetwo sockets...
            } finally {
                System.out.println("closing...");
                socket.close();
            }
        } finally{
            s.close();
        }
    }
}
